package channelService

import (
	"errors"
	"gitee.com/fierce_wolf/go-fox-edge-common/commRedisRpc"
	"gitee.com/fierce_wolf/go-fox-edge-common/commUtil/Map"
	"go-fox-edge-channel-tcp-server-v2/channelEngine/channelManager"
	"go-fox-edge-channel-tcp-server-v2/channelEngine/channelParams"
	"go-fox-edge-channel-tcp-server-v2/channelService/reportService"
)

type channelService struct {
}

func (e *channelService) OpenChannel(channelName string, channelParam map[string]interface{}) error {
	deviceKey := Map.GetString(channelParam, "deviceKey", "")
	if deviceKey == "" {
		return errors.New("通道的配置参数不能为空: deviceKey")
	}

	channelParams.SetChannelName(deviceKey, channelName)
	channelParams.SetChannelParam(deviceKey, channelParam)
	return nil
}

func (e *channelService) CloseChannel(channelName string, channelParam map[string]interface{}) error {
	// 根据通道名称，获得之前保存的deviceKey
	if !channelParams.HasChannelName(channelName) {
		return nil
	}

	deviceKey := Map.GetString(channelParam, "deviceKey", "")

	// 使用deviceKey，获得tcp连接的上下文，然后关闭跟设备之间的连接
	ctx := channelManager.GetContextByServiceKey(deviceKey)
	if ctx != nil {
		ctx.Close()

		// 删除数据
		channelManager.RemoveByRemoteAddr(ctx.RemoteAddr().String())
	}

	// 删除通道名称和deviceKey的关系
	channelParams.DelChannelName(channelName)
	return nil
}

func (e *channelService) Publish(requestVO *commRedisRpc.ChannelRequestVO) error {
	serviceKey, ok := channelParams.GetDeviceKeyByChannelName(requestVO.Name)
	if !ok {
		return errors.New("参数不能为空: deviceKey")
	}

	ctx := channelManager.GetContextByServiceKey(serviceKey)
	if ctx == nil {
		return errors.New("找不到对应的socket连接: " + requestVO.Name + ", 出错原因-> 远端设备尚未主动连接或者未登陆认证serviceKey信息")
	}

	return publish.publish(ctx, requestVO)
}

func (e *channelService) Report() ([]*commRedisRpc.ChannelRespondVO, error) {
	return reportService.PopAll()
}
